package com.fenghuajueli.libbasecoreui.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;

import com.blankj.utilcode.util.LogUtils;

import java.io.IOException;

public class AudioPlayUtils {

    private static volatile AudioPlayUtils instance;
    private MediaPlayer mediaPlayer;
    private Context context;
    private Boolean isLoop=false;


    private AudioPlayUtils() {

    }

    public static AudioPlayUtils getInstance() {
        if (instance == null) {
            synchronized (AudioPlayUtils.class) {
                if (instance == null) {
                    instance = new AudioPlayUtils();
                }
            }
        }
        return instance;
    }

    public void init(Context context) {
        this.context = context;
    }


    /**
     * 播放assets目录下的音频
     *
     * @param assetsPath
     */
    public void play(String assetsPath) {
        isLoop = false;
        AssetManager assetManager = context.getAssets();
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        try {
            //打开音乐文件shot.mp3
            AssetFileDescriptor assetFileDescriptor = assetManager.openFd(assetsPath);
            mediaPlayer.reset();
            //设置媒体播放器的数据资源
            mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 播放assets目录下的音频
     *
     * @param assetsPath
     */
    public void play(String assetsPath, Boolean isLoop) {
        AssetManager assetManager = context.getAssets();
        this.isLoop = isLoop;
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        try {
            //打开音乐文件shot.mp3
            AssetFileDescriptor assetFileDescriptor = assetManager.openFd(assetsPath);
            mediaPlayer.reset();
            //设置媒体播放器的数据资源
            mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(mediaPlayer -> {
                if (this.isLoop) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void stop() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }

}
